package com.whzjkj.gateway.server.udp.listener;

import com.whzjkj.gateway.server.udp.handler.UDPServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: Mr.Hu
 * @create: 2018-10-29 16:10
 **/
@Component
@Slf4j
public class UDPServerListener {
    private Bootstrap bootstrap = new Bootstrap();
    private EventLoopGroup acceptGroup = new NioEventLoopGroup();

    public void start(){
        bootstrap.group(acceptGroup)
            .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>(){
                        @Override
                        protected void initChannel(NioDatagramChannel nioDatagramChannel) throws Exception {
                            ChannelPipeline pipeline = nioDatagramChannel.pipeline();
                            pipeline.addLast(new UDPServerHandler());
                        }
                    });
        try {
            ChannelFuture channelFuture = bootstrap.bind(11001).sync();
            log.info("UDP监听服务启动·······");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            acceptGroup.shutdownGracefully();
        }
    }

}
